package com.kurumi.autoprint.controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kurumi.autoprint.enums.ApiStatusEnum;
import com.kurumi.autoprint.enums.ArcStatusEnum;
import com.kurumi.autoprint.enums.ResponseStatusEnum;
import com.kurumi.autoprint.pojo.InpatientInfo;
import com.kurumi.autoprint.pojo.InpatientRecord;
import com.kurumi.autoprint.pojo.MrBasic;
import com.kurumi.autoprint.pojo.MrPrintDetail;
import com.kurumi.autoprint.pojo.MrPrintDto;
import com.kurumi.autoprint.pojo.MrPrintType;
import com.kurumi.autoprint.service.MedRecordService;
import com.kurumi.autoprint.service.WebService;
import com.kurumi.autoprint.service.order.PrintMrOrderService;
import com.kurumi.autoprint.util.ExceptionUtil;
import com.kurumi.autoprint.util.JsonUtil;
import com.kurumi.autoprint.util.MD5;
import com.kurumi.autoprint.util.PDFAndBase64ConvertUtil;
import com.kurumi.autoprint.util.Result;
import com.kurumi.autoprint.util.StringUtil;

@Controller
@RequestMapping("/print")
public class AutoPrintController {
	
	private Logger logger = LoggerFactory.getLogger(AutoPrintController.class);

	//webservice url 路径
	@Value("${webservice.getInpatientRecordsByIdNo.url}")
	private String getInpatientRecordServiceUrl;

	//webservice  方法名
	@Value("${webservice.getInpatientRecordsByIdNo.method}")
	private String getInpatientRecordMethod;

	
	@Value("${webservice.getInpatientRecordsByIdNo.param}")
	private String getInpatientRecordParam;

	@Value("${webservice.getPrintPatientInfo.method}")
	private String getPrintPatientInfoMethod;

	@Value("${webservice.getReportFile.method}")
	private String getReportFileMethod;
	
	//打印单价
	@Value("${PRINT_PIECE_FEE}")
	private String printPieceFee;

	@Autowired
	private MedRecordService medRecordService;
	
	@Autowired
	private PrintMrOrderService printMrOrderService;
	
	@Value("${interface.getPrintFeeAndPrintPage}")
	private String interafaceGetPrintFeeAndPrintPage;
	
	@Value("${interface.sendMessage}")
	private String interfaceSendMessage;

	@RequestMapping("/index")
	public String login(Model model) {
		return "print/index";
	}

	
	/**
	 * 根据身份证号查询患者住院信息
	 * @param idCard
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getMrRecordByIdCard")
	public Result getMrRecordByIdCard(String idCard) {
		Result result = null;
		
		
		System.out.println("idCard=" + idCard);
		idCard="370627197012174410";
		
		System.out.println("idCard=" + idCard);

		try {
			if (!StringUtils.isNotBlank(idCard)) {
				result = new Result(false, "身份证号不可为空!");
				return result;
			}
			
			if(!StringUtil.isValidIdNo(idCard.trim())) {
				result = new Result(false, "不是合法的身份证!");
				return result;
			}
			
			//生产
			if(interafaceGetPrintFeeAndPrintPage.equals(ApiStatusEnum.PRODUCE.getValue())) {
				List<MrBasic> mrBasicList = medRecordService.getMrBasicByIdCard(idCard.trim(),ArcStatusEnum.ARC_STATUS_ARCHIVED.getValue());
				result = new Result(true, "根据身份证号查询住院信息成功!", mrBasicList, 200);
			}else {
				//测试
				List<MrBasic> mrBasicList = new ArrayList<MrBasic>();
				MrBasic mrBasic = new MrBasic();
				mrBasic.setLinkPhone("15027051180");
				mrBasic.setIdCard("370622194802213116");
				mrBasic.setOutDeptName("呼吸科");
				mrBasic.setName("test");
				mrBasic.setOnlyId("1234");
				mrBasic.setMrId("8888");
				mrBasic.setInTime(new Date());
				mrBasic.setOutTime(new Date());
				mrBasic.setId(1);
				mrBasicList.add(mrBasic);
				
				
				MrBasic mrBasic1 = new MrBasic();
				mrBasic1.setLinkPhone("15027051180");
				mrBasic1.setIdCard("370622194802213116");
				mrBasic1.setOutDeptName("呼吸科");
				mrBasic1.setName("test");
				mrBasic1.setOnlyId("1234");
				mrBasic1.setMrId("8888");
				mrBasic1.setInTime(new Date());
				mrBasic1.setOutTime(new Date());
				mrBasic1.setId(2);
				mrBasic1.setInNumber((short)1);
				mrBasicList.add(mrBasic1);
				result = new Result(true, "根据身份证号查询住院信息成功!", mrBasicList, 200);
			}
			
			logger.info("根据身份证号查询住院信息成功!");
		} catch (Exception e) {
			logger.error("-----根据身份证号查询患者住院信息----exceptionMsg=" + ExceptionUtil.getStackTrace(e));
			result = new Result(false, "系统异常" + ExceptionUtil.getStackTrace(e), null, 500);
		} 
		
		return result;
	}
	
	/**
	 * 生成短信验证码并返回给前台
	 * 
	 * @return
	 */
	@ResponseBody
	@PostMapping("/sendMessage")
	private Result sendMessage(String idCard, String phone) {
		Result result = null;
		idCard="370627197012174410";
		phone="15200192985";
		
		if (StringUtils.isBlank(idCard) || StringUtils.isBlank(phone)) {
			result = new Result(false, "身份证号和手机号不可为空!");
			return result;
		}
		
//		if (!StringUtil.isMobile(phone.trim())) {
//			result = new Result(false, "不是合法的手机号!");
//		}
		String messageCode = StringUtil.rand();
		//生产
		if(interfaceSendMessage.equals(ApiStatusEnum.PRODUCE.getValue())) {
			 medRecordService.sendMessage(phone, messageCode);
		}
	
		
		logger.info("" + phone + "验证码:" + messageCode + ",有效期为3分钟，请妥善保管您的验证码，请勿将验证码泄露给他人!");
		// 保存短信日志信息
		medRecordService.addMessageLog(idCard, phone, messageCode);
		result = new Result(true, "获取验证码成功!", messageCode, 200);

		return result;
	}

	/**
	 * 验证短信验证码
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/validateMessage")
	private Result sendMessage(String idCard, String phone, String code) {
		idCard="370627197012174410";
		phone="15200192985";
		Result result = null;
		if (StringUtils.isEmpty(idCard) || StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
			result = new Result(false, "身份证号、手机号、验证码不可为空!");
			return result;
		}
		logger.info("----------------前台短信验证信息为---------------------------:" + code);

		if (medRecordService.validateMessageCode(idCard, phone, code)) {
			logger.info("身份证号:"+idCard+" 电话:"+phone+"短信验证码验证成功");
			result = new Result(true, "短信验证码验证成功!");
			return result;
		}

		return new Result(false, "短信验证码验证失败!");
	}
	
	
	/**
	 * 获取打印类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPrintType")
	public Result getPrintType() {
		Result result = null;
		try {
			List<MrPrintType> mrPrintTypeList  = new ArrayList<>();
			//生产
			if(interafaceGetPrintFeeAndPrintPage.equals(ApiStatusEnum.PRODUCE.getValue())) {
				mrPrintTypeList = medRecordService.getPrintTypes();
			}else {
				MrPrintType mrPrintType1 = new MrPrintType();
				mrPrintType1.setCode(33);
				mrPrintType1.setName("常规打印(无检验)");
				mrPrintTypeList.add(mrPrintType1);
				
				MrPrintType mrPrintType2 = new MrPrintType();
				mrPrintType2.setCode(34);
				mrPrintType2.setName("常规打印(有检验)");
				mrPrintTypeList.add(mrPrintType2);
				
			}
			
			logger.info("----------查询打印字典成功!----------------------");
			result = new Result(true,"查询打印类型成功!",mrPrintTypeList);
		} catch (Exception e) {
			result = new Result(false,"查询打印类型失败!");
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * 根据打印类型和打印份数计算费用信息
	 * @param request
	 * @param mrBasicId
	 * @param printCode
	 * @param printNum
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPrintFeeAndPrintPage")
	public Result getPrintFeeAndPrintPage(HttpServletRequest request, String mrBasicId, String printType, Integer printCopy) {
		Result result = null;
		
		try {
			//根据mrBasicId获取病案文件信息，并计算打印费用和返回打印文件路径
			if (interafaceGetPrintFeeAndPrintPage.equals(ApiStatusEnum.PRODUCE.getValue())) {
				MrPrintDto mrPrintDto = medRecordService.getPrintFeeAndPrintPath(mrBasicId, printType, printCopy, printPieceFee, null);
				result = new Result(true,"打印费用查询成功!",mrPrintDto);
			} else if (interafaceGetPrintFeeAndPrintPage.equals(ApiStatusEnum.TEST.getValue())) {
				String pdfPath = "D://xxxx.pdf";
				
				MrPrintDto mrPrintDto = new MrPrintDto();
				mrPrintDto.setMrBasicId("1");
				mrPrintDto.setPrintTotalFee(new BigDecimal(1));
				mrPrintDto.setTotalPrintPage(30);
				String pdfBase64 = PDFAndBase64ConvertUtil.pdfToBase64(new File(pdfPath));
				
				if (StringUtils.isBlank(pdfBase64)) {
					return new Result(false, "打印pfd出错", ResponseStatusEnum.PDF_TRANSFER_ERROR.getValue());
				}
				
				//mrPrintDto.setPrintPDFbase64(pdfBase64);
				result = new Result(true,"打印费用查询成功!", mrPrintDto, ResponseStatusEnum.SUCCESS.getValue());
			} else {
				logger.error("--调用getPrintFeeAndPrintPage接口获取根据打印类型和打印份数计算费用信息  配置文件interafaceGetPrintFeeAndPrintPage的值错误--");
				return new Result(false, "配置文件配置的interafaceGetPrintFeeAndPrintPage错误!", null, ResponseStatusEnum.SYSTEM_ERROR.getValue());
			}
		} catch (Exception e) {
			logger.error("根据打印类型和打印份数计算费用信息失败:" + ExceptionUtil.getStackTrace(e));
			result = new Result(false,"打印费用计算失败" + ExceptionUtil.getStackTrace(e), null, ResponseStatusEnum.SYSTEM_ERROR.getValue());
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * 保存打印详情信息
	 * @param
	 * 		mrPrintDetail
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addMrPrintDetail")
	public Result addMrPrintDetail(MrPrintDetail mrPrintDetail) {
		Result result = null;
		logger.info("------------------进入保存打印详情信息--------------");
		try {
			medRecordService.addMrPrintDetail(mrPrintDetail);
			result = new Result(true,"打印详情保存成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false,"打印详情保存失败!");
			logger.error("打印详情保存失败!错误信息："+e.getMessage());
		}
		return result;
	}
	
	
	@ResponseBody
	@RequestMapping("/getPrintPDFBase64ByMrBasicIdAndPrintType")
	public Result getPrintPDFBase64ByMrBasicIdAndPrintType(String mrBasicId,String printTypeCode, String ipAddress) {
		try {
//			mrBasicId="431929";
//			printTypeCode="33";
//			ipAddress="127.0.0.1";
			if(StringUtils.isEmpty(mrBasicId) || StringUtils.isEmpty(printTypeCode)) {
				return new Result(false,"唯一标识和打印类型不可为空!",ResponseStatusEnum.PARAM_VERIFY.getValue());
			}
			
			Result convertResult = null;
			
			if (interafaceGetPrintFeeAndPrintPage.equals(ApiStatusEnum.PRODUCE.getValue())) {
				//convertResult =	medRecordService.convertPDF2Base64(mrBasicId,printTypeCode, ipAddress);
				convertResult =	medRecordService.convertPDF2Imgs(mrBasicId,printTypeCode, ipAddress);
				return convertResult;
			}else {
				//File file = new File("D://publics/print/c84ea8d3dde7130386098a18d0f2759d.PDF");
				convertResult =	medRecordService.convertPDF2Imgs(mrBasicId,printTypeCode, ipAddress);
				return convertResult;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"系统异常:"+e.getMessage(),500);
		}
	}
	
	@ResponseBody
	@PostMapping("/getDelay")
	public Result getDelay(Integer delayMill) {
		try {
			Thread.sleep(delayMill);
		} catch (Exception e) {
			logger.error("延迟时间异常, exceptionMsg={}" + ExceptionUtil.getStackTrace(e));
		}
		
		return new Result(true, "延迟");
	}
	
	@ResponseBody
	@PostMapping("/updatePrintStatus")
	public Result updatePrintStatus(String orderNum, Integer printStatus, String printErrorMsg) {
		try {
			if (printMrOrderService.updatePrintStatusByOrderNum(orderNum, printStatus, printErrorMsg) > 0) {
				return new Result(true, "成功", null, 200);
			}
			
			return new Result(false, "失败", null, 500);
		} catch (Exception e) {
			logger.error("订单号={}, 要修改成打印状态={}, exceptionMsg={}",
					orderNum, printStatus, ExceptionUtil.getStackTrace(e));
			
			return new Result(false, "系统异常" + ExceptionUtil.getStackTrace(e), null, 500);
		}
	}
	

/*	@RequestMapping("/mrRecordPage")
	public String showInfo(Model model) throws IllegalAccessException {
		InpatientInfo inpatientInfo = webService.testService(getInpatientRecordServiceUrl, getInpatientRecordMethod,
				getInpatientRecordParam);
		if (inpatientInfo != null) {

			List<InpatientRecord> inpatientRecords = inpatientInfo.getInpatientRecords();
			model.addAttribute("list", inpatientRecords);

		}
		return "print/mrRecordPage";
	}

	@ResponseBody
	@RequestMapping("/show")
	public String showpage(String id) {

		PrintPatientInfo printPatientInfo = webService.getInpatientRecord(getInpatientRecordServiceUrl,
				getPrintPatientInfoMethod, id);
		List<ReportRecord> reportRecords = printPatientInfo.getReportInfos();

		Collections.sort(reportRecords, new Comparator<ReportRecord>() {

			@Override
			public int compare(ReportRecord o1, ReportRecord o2) {
				return Integer.parseInt(o1.getReportId()) - Integer.parseInt(o2.getReportId());
			}
		});

		for (ReportRecord reportRecord : reportRecords) {
			String filePath = reportRecord.getFilePath();
			String fileName = reportRecord.getFileName();

			ReportFile reportFile = webService.getReportFile(getInpatientRecordServiceUrl, getReportFileMethod,
					filePath + fileName);

			System.out.println(reportFile.getStream());
		}

		return JsonUtil.objectToJson(printPatientInfo);
	}
	*/
}
